import SparkMD5 from 'spark-md5';
// import { uploadSplit } from '@/api/demoUpload'

// const SIZE = 10 * 1024 * 1024 // 切片大小 5m
export class CreateFileMd5 {
  constructor() {
    this.formDataList= [] // 请求列表
    this.overTime = 0 // 失败循环次数
    this.fileMd5 = '' // 文件的md5
  }

  calMd5(file) {
    return new Promise((resolve) => {
      let fileReader = new FileReader(),
      blobSlice =
              File.prototype.mozSlice ||
              File.prototype.webkitSlice ||
              File.prototype.slice,
          chunkSize = 2097152,
          // read in chunks of 2MB
          chunks = Math.ceil(file.size / chunkSize),
          currentChunk = 0,
          spark = new SparkMD5(),
          that = this
      fileReader.onload = (e) => {
          spark.appendBinary(e.target.result)
          // append binary string
          currentChunk++
          if (currentChunk < chunks) {
              loadNext()
          } else {  // 计算分片能完成之后，才开始上传
              let md = spark.end()
              that.fileMd5 = md
              that.beginUpload(file)  // 开始切片，和处理相关参数
              resolve(that.formDataList)
          }
      }
      function loadNext () {
        let start = currentChunk * chunkSize,
            end = start + chunkSize >= file.size ? file.size : start + chunkSize;
        fileReader.readAsBinaryString(blobSlice.call(file, start, end));
      }
      loadNext()
    })
  }

  // 根据文件大小获取分片的大小
  getSizeByFileSize() {
    return 5 * 1024 * 1024
  }

  // 生成文件切片
  createFileChunk(fileInstance) {
    const pathSize = this.getSizeByFileSize() // 获取每一片的大小
    const fileMd5 = this.fileMd5  // 文件的md5
    const fileChunkList = []  // 保存每一片
    const { size } = fileInstance
    let cur = 0
    let index = 0 // 下标
    while (cur < size) {
      fileChunkList.push({ 
        chunk: fileInstance.slice(cur, cur + pathSize),
        chunkIndex: index,
        chunkSize : pathSize,  // 每一片的大小
        fileMd5
      })
      cur += pathSize
      index += 1
    }
    return fileChunkList
  }

  // 上传
  beginUpload(file) {
    const chunkList = this.createFileChunk(file)  // 获取切片的结果列表
    const chunks = chunkList.length
    const formDataList = chunkList.map(({ chunk, chunkIndex, chunkSize, fileMd5 }) => {
      const formData = new FormData()
      formData.append("file", chunk)
      formData.append("md5FileVO", JSON.stringify({
        chunk: chunkIndex,  // 当前片的下标
        chunks, // 分片的数量
        chunkSize,
        fileType: '1',
        fileMd5,
        fileName: file.name
      }))
      return formData
    })
    this.formDataList = formDataList // 把请求列表反出去，在外面请求
  }
}
